<?php
/**
 * Created by PhpStorm.
 * User: xk_96
 * Date: 2018/1/16
 * Time: 16:37
 */

namespace system\lib;


class WxApi
{
    private $config = [];
    //获取code
    private $getCodeUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
    //用code获取token
    private $getTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
    //获取用户信息
    private $getUserInfo = 'https://api.weixin.qq.com/sns/userinfo?';
    //回调链接
    private $redirectUri = null;

    public function __construct()
    {
        $this->redirectUri = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .'?c=wx&do=index&'. 'callbackurl=';
        //初始化微信配置文件
        $wxConfigPath = BASE_ROOT . '/app/config/wx.php';
        if (file_exists($wxConfigPath)) {
            $this->config = include $wxConfigPath;
        } else {
            die("找不到微信配置文件");
        }
    }

    public function OAuth($callBack, $isInfo)
    {
        /*第一步：用户同意授权，获取code*/
        $parameter = array(
            'appid' => $this->config['appId'],
            'redirect_uri' => $this->redirectUri . $callBack,
            'response_type' => 'code'
        );
        $parameter['scope'] = $isInfo ? 'snsapi_userinfo' : 'snsapi_base';
        $parameter['state'] = $isInfo ? '1' : '0';
        $url = $this->getCodeUrl . http_build_query($parameter) . '#wechat_redirect';
        header('location:'.$url);
    }

    public function getToken(){
        //第二步：通过code换取网页授权access_token
        $code = $_REQUEST['code'];
        $parameter = array(
            'appid' => $this->config['appId'],
            'secret' => $this->config['appSecret'],
            'code' => $code,
            'grant_type' => 'authorization_code'
        );
        $url = $this->getTokenUrl . http_build_query($parameter);
        $http = new Http();
        return $http->sendGet($url);
    }

    public function getUserInfo($accessToken,$openId){
        //第四步：拉取用户信息(需scope为 snsapi_userinfo)
        $parameter = array(
            'access_token' => $accessToken,
            'openid' => $openId,
            'lang' => 'zh_CN'
        );
        $url = $this->getUserInfo . http_build_query($parameter);
        $http = new Http();
        return $http->sendGet($url);
    }
    public function getWxUserInfo(){
        session_start();
        if(isset($_SESSION['WxUserInfo'])){
            return $_SESSION['WxUserInfo'];
        }
        if ($_REQUEST['code'] == ''){
            $this->OAuth('',true);
        }else{
            $token = $this->getToken();
            $token = json_decode($token);
            $userInfo = $this->getUserInfo($token->access_token,$token->openid);
            $userInfo = json_decode($userInfo);
            $_SESSION['WxUserInfo'] = $userInfo;
            return $userInfo;
        }
    }
}